<template>
  <div>
    <div v-mydrag id="box">
      <div class="header"></div>
      <div class="body"></div>
    </div>
  </div>
</template>

<script>

export default {
  name: "MyDrag",
  data() {
    return {
      flag: false,
    }
  },
  directives: {
    'mydrag': {
      bind(boxDom) {

        const headerDom = boxDom.querySelector(".header")
        let flag = false;
        let x, y;

        headerDom.addEventListener("mousedown", (event) => {
          flag = true;
          x = event.offsetX;
          y = event.offsetY;
        })

        // 将mousemove事件加在 document上是为了解决快速拖拽时鼠标脱离div的bug
        document.addEventListener("mousemove", (event) => {
          if (flag) {
            let _h = window.innerHeight - boxDom.offsetHeight;
            let _w = window.innerWidth - boxDom.offsetWidth;
            let move_x = event.clientX - x;
            let move_y = event.clientY - y;

            move_y = Math.min(Math.max(0, move_y), _h);
            move_x = Math.min(Math.max(0, move_x), _w);

            boxDom.style.left = move_x + "px";
            boxDom.style.top = move_y + "px";
          }
        })

        headerDom.addEventListener("mouseup", () => {
          flag = false;
        })

      }
    }
  }
}
</script>

<style scoped>
#box {
  width: 300px;
  height: 200px;
  background: skyblue;
  position: absolute;
}

.header {
  height: 30px;
  background-color: antiquewhite;
  cursor: move;
}
</style>